package com.springboot.sql.service.impl;

import com.springboot.constants.RoleConstants;
import com.springboot.constants.UserConstants;
import com.springboot.core.OperatorResult;
import com.springboot.sql.dao.TSysRoleDao;
import com.springboot.sql.dao.TSysUserDao;
import com.springboot.sql.dao.entity.SysRole;
import com.springboot.sql.dao.entity.SysUser;
import com.springboot.sql.service.IUserService;
import com.springboot.utils.PasswordHash;
import com.springboot.vo.req.AddUserReq;
import com.springboot.vo.req.UpdateUserPasReq;
import com.springboot.vo.req.UpdateUserReq;
import com.springboot.vo.res.CusUserResp;
import com.springboot.vo.res.ZTree;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * On 2017/3/13 0013.
 */
@Service
public class UserServiceImpl implements IUserService{
    private final TSysUserDao tSysUserDao;
    private final TSysRoleDao tSysRoleDao;
    @Autowired
    public UserServiceImpl(TSysUserDao tSysUserDao, TSysRoleDao tSysRoleDao) {
        this.tSysUserDao = tSysUserDao;
        this.tSysRoleDao = tSysRoleDao;
    }

    @Override
    public List<CusUserResp> getAllCusUsers() {
        SysUser condition= new SysUser();
        //自定义用户标志
        condition.setUserType(UserConstants.CUSTOM_USER);
        return tSysUserDao.find(condition).stream().map(m->{
            CusUserResp cusUserResp= new CusUserResp();
            cusUserResp.setUsername(m.getUsername());
            cusUserResp.setRealname(m.getRealName());
            cusUserResp.setEmail(m.getEmail());
            return cusUserResp;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ZTree> getUserRoles(String username) {
        List<SysRole> sysRoles=tSysRoleDao.findUserRoles(username);
        List<ZTree> zTrees= new ArrayList<>(sysRoles.size()+2);
        //添加两个默认的根节点，自定义角色和系统默认角色
        ZTree custom=new ZTree(RoleConstants.ROOT_CUSTOM_ID,null,RoleConstants.ROOT_CUSTOM_NAME,false);
        ZTree system=new ZTree(RoleConstants.ROOT_SYSTEM_ID,null,RoleConstants.ROOT_SYSTEM_NAME,false);
        zTrees.add(custom);
        zTrees.add(system);
        for (SysRole sysRole : sysRoles){
            ZTree zTree =new ZTree();
            zTree.setName(sysRole.getRoleRealName());
            zTree.setId(sysRole.getRoleId());
            zTree.setChecked(sysRole.getHave());
            //根据不同标志分配到不同节点下
            if (sysRole.getRoleFlag().equals(RoleConstants.UNSYSTEM_FLAG)){
                zTree.setpId(RoleConstants.ROOT_CUSTOM_ID);
            }
            else {
                zTree.setpId(RoleConstants.ROOT_SYSTEM_ID);
            }
            zTrees.add(zTree);
        }
        return zTrees;
    }

    @Override
    public OperatorResult insertUser(@Valid AddUserReq addUserReq) {
        SysUser condition= new SysUser();
        condition.setUserName(addUserReq.getUserName());
        List<SysUser> result;
        //检查用户是否已经存在
        if ((result = tSysUserDao.find(condition)) != null && result.size() < 1){
            SysUser sysUser = new SysUser();
            sysUser.setUserName(addUserReq.getUserName());
            sysUser.setPassword(UserConstants.INIT_PASSWORD);
            sysUser.setUserType(UserConstants.CUSTOM_USER);
            sysUser.setSex(UserConstants.INIT_SEX);
            sysUser.setUserStatus(UserConstants.INIT_STATUS);
            sysUser.setEmail(addUserReq.getEmail());
            sysUser.setRealName(addUserReq.getRealName());
            //先插入用户表
            if (tSysUserDao.insert(sysUser)>0){
                //授权用户对应的角色
                if (tSysUserDao.authRoles(sysUser.getUsername(),addUserReq.getNeedRoles())>0)
                    return OperatorResult.SUCCESS();
                return OperatorResult.ERROR();
            }
            return OperatorResult.ERROR();
        }
        return OperatorResult.ERROR(UserConstants.OPT_USER_EXIST_ERROR);
    }

    @Override
    public OperatorResult updateUser(@Valid UpdateUserReq updateUserReq) {
        SysUser condition = new SysUser();
        condition.setUserName(updateUserReq.getUsername());
        //只处理自定义用户，系统默认用户不处理
        condition.setUserType(UserConstants.CUSTOM_USER);
        List<SysUser> sysUsers=tSysUserDao.find(condition);
        if (sysUsers!=null&&sysUsers.size()>0){
            SysUser sysUser = sysUsers.get(0);
            sysUser.setRealName(updateUserReq.getRealName());
            sysUser.setEmail(updateUserReq.getEmail());
            if (tSysUserDao.update(sysUser)>0) {
                //角色列表更新
                List<String> addRoles= new ArrayList<>();
                List<String> deleteRoles= new ArrayList<>();
                updateUserReq.getUpdateRoles().forEach(m->{
                    if (m.getChecked())
                        addRoles.add(m.getId());
                    else
                        deleteRoles.add(m.getId());
                });
                if (addRoles.size()>0)
                    tSysUserDao.authRoles(sysUser.getUsername(),addRoles);
                if(deleteRoles.size()>0)
                    tSysUserDao.unAuthRoles(sysUser.getUserName(),deleteRoles);
                return OperatorResult.SUCCESS();
            }
            return OperatorResult.ERROR(UserConstants.OPT_USER_UPDATE_ERROR);
        }
        return OperatorResult.ERROR(UserConstants.OPT_USER_NOEXIST_ERROR);
    }

    @Override
    public OperatorResult deleteUser(List<String> usernames) {
        SysUser condition = new SysUser();
        condition.setUserType(UserConstants.CUSTOM_USER);
        for (String username : usernames){
            //验证是自定义用户
            if (tSysUserDao.find(condition).size()>0){
                tSysUserDao.unAuthRoles(username,null);
                tSysUserDao.deleteByUsername(username);
            }
        }
        return OperatorResult.SUCCESS();
    }

    @Override
    public OperatorResult initPassWord(String username) {
        if (StringUtils.isNoneBlank(username)){
            //验证是否为自定义帐号
            SysUser condition = new SysUser();
            condition.setUserName(username);
            condition.setUserType(UserConstants.CUSTOM_USER);
            if (tSysUserDao.find(condition).size()>0) {
                condition.setPassword(UserConstants.INIT_PASSWORD);
                tSysUserDao.update(condition);
                return OperatorResult.SUCCESS();
            }
        }
        return OperatorResult.ERROR(UserConstants.OPT_USER_NOEXIST_ERROR);
    }

    @Override
    public OperatorResult updatePassWord(@Valid UpdateUserPasReq updateUserPasReq) {
        SysUser condition = new SysUser();
        condition.setUserName(updateUserPasReq.getUsername());
        List<SysUser> sysUsers=tSysUserDao.find(condition);

        if (sysUsers!=null&&sysUsers.size()>0){
            SysUser sysUser = sysUsers.get(0);
            try {
                if (PasswordHash.validatePassword( updateUserPasReq.getOldPass(),sysUser.getPassword())) {
                    sysUser.setPassword(PasswordHash.createHash(updateUserPasReq.getNewPass()));
                    tSysUserDao.update(sysUser);
                    return OperatorResult.SUCCESS();
                }
            }catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                e.printStackTrace();
                return OperatorResult.ERROR("系统错误");
            }
            return OperatorResult.ERROR("旧密码错误");
        }
        return OperatorResult.ERROR("账号不存在");
    }
}
